package com.cy.aircompressor.main.home.fragment.provider;

import android.content.Context;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.fragment.app.FragmentManager;

import com.cy.aircompressor.databinding.ItemTemperaturePressureChangeTrendBinding;
import com.cy.aircompressor.entity.linechart.LineChartEntry;
import com.cy.aircompressor.entity.sensor.SensorAgg;
import com.cy.aircompressor.entity.sensor.SensorItemData;
import com.cy.aircompressor.entity.sensor.SensorLineChartData;
import com.cy.aircompressor.entity.sensor.SensorLatestData;
import com.cy.aircompressor.entity.sensor.SensorStatisticsData;
import com.cy.aircompressor.main.home.dialog.LineChartFullScreenDialog;
import com.cy.aircompressor.main.ui.onlinemonitor.utils.LineChartUtil;
import com.drug.lib.view.recycptr.ItemViewBinder;
import com.github.mikephil.charting.data.Entry;
import com.jakewharton.rxbinding2.view.RxView;
import com.net.model.base.BaseBindViewHolder;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.function.Predicate;
import java.util.stream.Collectors;

public class TemperaturePressureProvider extends ItemViewBinder<SensorLineChartData, TemperaturePressureProvider.ViewHolder> {
    Context mContext;
    FragmentManager fragmentManager;

    public TemperaturePressureProvider(FragmentManager fragmentManager, Context mContext) {
        this.mContext = mContext;
        this.fragmentManager = fragmentManager;
    }


    @NonNull
    protected TemperaturePressureProvider.ViewHolder onCreateViewHolder(@NonNull LayoutInflater inflater, @NonNull ViewGroup parent) {
        return new ViewHolder(ItemTemperaturePressureChangeTrendBinding.inflate(inflater, parent, false));
    }

    @Override
    protected void onBindViewHolder(@NonNull TemperaturePressureProvider.ViewHolder holder, @NonNull SensorLineChartData entity) {
        if (entity.getSensorAggs() != null) {
            List<LineChartEntry> lineChartEntries = new ArrayList<>();
            for (SensorAgg sensorAgg : entity.getSensorAggs()) {
                List<SensorStatisticsData> sensorStatisticsData = sensorAgg.getSensorStatisticsData();
                if (sensorStatisticsData != null && sensorStatisticsData.size() != 0) {
                    LineChartEntry lineChartEntry = sensorAgg.getLineChartEntry();
                    lineChartEntry.setEntrys(getChartEntry(sensorStatisticsData));
                    String color = getColor(sensorAgg, entity.getPointCode());
                    lineChartEntry.setColor(color);
                    lineChartEntries.add(lineChartEntry);
//                    LineChartUtil.addAndUpdateLine(holder.mBinding.lineChart, lineChartEntry);
                }
            }
            if (lineChartEntries == null || (lineChartEntries != null && lineChartEntries.size() == 0)) {
                LineChartUtil.addEmptyLine(holder.mBinding.lineChart);
            } else {
                LineChartUtil.addAndUpdateLine(holder.mBinding.lineChart, lineChartEntries);
            }
        } else {
            LineChartUtil.addEmptyLine(holder.mBinding.lineChart);
        }
        LineChartUtil.checkLineChart(holder.mBinding.lineChart);

        setDefault(holder, entity);
        setRealTimeData(holder, entity);
        RxView.clicks(holder.mBinding.fullScreen)
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(o -> {
                    LineChartFullScreenDialog.showDialogFragment(fragmentManager, "full", entity);
                });

    }


    /**
     * 设置最新数据
     *
     * @param holder
     * @param entity
     */
    private void setRealTimeData(ViewHolder holder, SensorLineChartData entity) {
        SensorLatestData sensorLatestData = entity.getSensorLatestData();
        if (sensorLatestData == null) {
            holder.mBinding.cylinder1stValue.setText("-");
            holder.mBinding.cylinder2stValue.setText("-");
            holder.mBinding.cylinder3stValue.setText("-");
        } else {
            if (!TextUtils.equals(entity.getPointCode(), "pressure_water,pressure_oil")) {
                SensorItemData sensorItemData = getSensorItemData("cylinder_1st", entity.getPointCode(), sensorLatestData.getDataList());
                if (sensorItemData == null) {
                    holder.mBinding.cylinder1stValue.setText("-");
                } else {
                    holder.mBinding.cylinder1stValue.setText(sensorItemData.getV());
                }
                sensorItemData = getSensorItemData("cylinder_2nd", entity.getPointCode(), sensorLatestData.getDataList());
                if (sensorItemData == null) {
                    holder.mBinding.cylinder2stValue.setText("-");
                } else {
                    holder.mBinding.cylinder2stValue.setText(sensorItemData.getV());
                }
                sensorItemData = getSensorItemData("cylinder_3rd", entity.getPointCode(), sensorLatestData.getDataList());
                if (sensorItemData == null) {
                    holder.mBinding.cylinder3stValue.setText("-");
                } else {
                    holder.mBinding.cylinder3stValue.setText(sensorItemData.getV());
                }
            } else {
                SensorItemData sensorItemData = getSensorItemData("body", "pressure_oil", sensorLatestData.getDataList());
                if (sensorItemData == null) {
                    holder.mBinding.cylinder1stValue.setText("-");
                } else {
                    holder.mBinding.cylinder1stValue.setText(sensorItemData.getV());
                }
                sensorItemData = getSensorItemData("body", "pressure_water", sensorLatestData.getDataList());
                if (sensorItemData == null) {
                    holder.mBinding.cylinder2stValue.setText("-");
                } else {
                    holder.mBinding.cylinder2stValue.setText(sensorItemData.getV());
                }
            }
        }
    }

    private SensorItemData getSensorItemData(String partCode, String pointCode, List<SensorItemData> dataList) {
        if (dataList == null)
            return null;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
            List<SensorItemData> sensorItemDataList = dataList.stream()
                    .filter(new Predicate<SensorItemData>() {
                        @Override
                        public boolean test(SensorItemData sensorItemData) {
                            return TextUtils.equals(sensorItemData.getCompressorPartCode(), partCode) &&
                                    TextUtils.equals(sensorItemData.getCompressorPointCode(), pointCode);
                        }
                    }).collect(Collectors.toList());
            if (sensorItemDataList != null && sensorItemDataList.size() > 0) {
                return sensorItemDataList.get(0);
            }
        }
        return null;

    }


    /**
     * 设置默认值
     *
     * @param holder
     * @param entity
     */
    private void setDefault(ViewHolder holder, SensorLineChartData entity) {
        switch (entity.getPointCode()) {
            case "temperature":
                holder.mBinding.titleName.setText("温度变化趋势");
                holder.mBinding.textUnit.setText("℃");
                holder.mBinding.labeled1.setText("一级气缸");
                holder.mBinding.labeled2.setText("二级气缸");
                holder.mBinding.labeled3.setText("三级气缸");
                holder.mBinding.labeled3.setVisibility(View.VISIBLE);
                holder.mBinding.labeled3Dot.setVisibility(View.VISIBLE);

                holder.mBinding.cylinder1stName.setText("一级气缸温度");
                holder.mBinding.cylinder1stUnit.setText("℃");
                holder.mBinding.cylinder2stName.setText("二级气缸温度");
                holder.mBinding.cylinder2stUnit.setText("℃");
                holder.mBinding.cylinder3stName.setText("三级气缸温度");
                holder.mBinding.cylinder3stUnit.setText("℃");
                holder.mBinding.cylinder3stLayout.setVisibility(View.VISIBLE);

                break;
            case "pressure":
                holder.mBinding.titleName.setText("压力变化趋势");
                holder.mBinding.textUnit.setText("Mpa");
                holder.mBinding.labeled1.setText("一级气缸");
                holder.mBinding.labeled2.setText("二级气缸");
                holder.mBinding.labeled3.setText("三级气缸");
                holder.mBinding.labeled3.setVisibility(View.VISIBLE);
                holder.mBinding.labeled3Dot.setVisibility(View.VISIBLE);

                holder.mBinding.cylinder1stName.setText("一级气缸压力");
                holder.mBinding.cylinder1stUnit.setText("Mpa");
                holder.mBinding.cylinder2stName.setText("二级气缸压力");
                holder.mBinding.cylinder2stUnit.setText("Mpa");
                holder.mBinding.cylinder3stName.setText("三级气缸压力");
                holder.mBinding.cylinder3stUnit.setText("Mpa");
                holder.mBinding.cylinder3stLayout.setVisibility(View.VISIBLE);
                break;
            case "pressure_water,pressure_oil":
                holder.mBinding.titleName.setText("油压,水压变化趋势");
                holder.mBinding.textUnit.setText("Mpa");
                holder.mBinding.labeled1.setText("油压");
                holder.mBinding.labeled2.setText("水压");
                holder.mBinding.labeled3.setVisibility(View.GONE);
                holder.mBinding.labeled3Dot.setVisibility(View.GONE);

                holder.mBinding.cylinder1stName.setText("油压");
                holder.mBinding.cylinder1stUnit.setText("Mpa");
                holder.mBinding.cylinder2stName.setText("水压");
                holder.mBinding.cylinder2stUnit.setText("Mpa");
                holder.mBinding.cylinder3stLayout.setVisibility(View.GONE);
                break;
        }
    }


    private String getColor(SensorAgg sensorAgg, String pointCode) {
        String color;
        if (!TextUtils.equals(pointCode, "pressure_water,pressure_oil"))
            color = getColor1(sensorAgg.getSensor().getCompressorPartCode());
        else
            color = get2Color(sensorAgg.getSensor().getCompressorPointCode());
        return color;
    }

    private String getColor1(String partCode) {
        switch (partCode) {
            case "cylinder_1st":
                return "#CF931F";
            case "cylinder_2nd":
                return "#CF1F5E";
            case "cylinder_3rd":
                return "#1F66CF";
            default:
                return "#FFFFFF";
        }
    }

    private String get2Color(String pointCode) {
        switch (pointCode) {
            case "pressure_oil":
                return "#CF931F";
            case "pressure_water":
                return "#CF1F5E";
            default:
                return "#FFFFFF";
        }
    }



    private List<Entry> getChartEntry(List<SensorStatisticsData> statisticsData) {
        List<Entry> entries = new ArrayList<>();
        if (statisticsData != null && statisticsData.size() != 0) {
            for (int i = 0; i < statisticsData.size(); i++) {
                SensorStatisticsData sensorStatisticsData = statisticsData.get(i);
                long time = getDate(sensorStatisticsData.getRt());
                Entry entry = new Entry(i, (float) sensorStatisticsData.getV(), time);
                entries.add(entry);
            }
        }
        return entries;
    }

    private long getDate(String rt) {
        Date date = null;
        try {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            date = format.parse(rt);
            return date.getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return 0;
    }

    public class ViewHolder extends BaseBindViewHolder<ItemTemperaturePressureChangeTrendBinding> {

        protected ViewHolder(ItemTemperaturePressureChangeTrendBinding itemView) {
            super(itemView);
            LineChartUtil.initLineChart(mBinding.lineChart, false);
        }
    }


}
